package com.wqh.ice_storm;

import com.wqh.ice_storm.ReportDemo.ReportServicePrx;
import com.wqh.ice_storm.ReportDemo.Weather;
import com.zeroc.Ice.Communicator;
import com.zeroc.Ice.ObjectPrx;
import com.zeroc.Ice.Util;
import com.zeroc.IceStorm.NoSuchTopic;
import com.zeroc.IceStorm.TopicExists;
import com.zeroc.IceStorm.TopicManagerPrx;
import com.zeroc.IceStorm.TopicPrx;
import java.util.logging.Logger;

public class Publisher {

    private static Logger logger = Logger.getLogger(Publisher.class.getSimpleName());

    public static void main(String[] args) {
        getWeather(args);
    }

    public static void getWeather(String[] args) {

        String topicName = "weather";
        //初始化通信器
        java.util.List<String> extraArgs = new java.util.ArrayList<>();
        try(Communicator com  = Util.initialize(args,"config.pub",extraArgs)){
            com.getProperties().setProperty("Ice.Default.Package","com.zeroc.demos.IceStorm.weather");

            //销毁通信器
            Runtime.getRuntime().addShutdownHook(new Thread(()->com.destroy()));


            //"IceStorm/TopicManager"对应发布端通信定义的名称
            //ObjectPrx obj = com.stringToProxy("WeatherService/TopicManager:tcp -h 192.168.10.1 -p 1888");
            ObjectPrx obj = com.propertyToProxy("TopicManager.Proxy");
            //让客户端订阅根据名称找到消息主题
            TopicManagerPrx topicManagerPrx = TopicManagerPrx.checkedCast(obj);

            TopicPrx topic =null;
            while(topic == null){
                try {
                    //尝试根据名称检索该主题
                    topic = topicManagerPrx.retrieve(topicName);
                } catch (NoSuchTopic noSuchTopic) {
                    //未找到订阅的主题，创建该主题
                    try {
                        topic = topicManagerPrx.create(topicName);
                    } catch (TopicExists topicExists) {
                        logger.info("其他客户端让服务端创建了该主题");
                        topicExists.printStackTrace();
                    }
                }
            }

            //取得publisher对象的代理,用单向通信方式
            ObjectPrx publisher = topic.getPublisher().ice_oneway();

            logger.info("发布端已经启动");
            //创建servant发布消息
            //为何会订阅这么多次呢？
            ReportServicePrx reportServicePrx = ReportServicePrx.uncheckedCast(publisher);
            while(true){
                Weather weather = new Weather();
                weather.temperature = 10.1f;
                weather.tower = "中央气象台";
                weather.windSpeed = 10;
                weather.windDirection = 1;
                //发布天气消息
                reportServicePrx.report(weather);

                //每发布一条消息，停顿一秒
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}
